package com.drusunlimited.input{
	
	import flash.events.ActivityEvent;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.media.Microphone;
	import flash.media.SoundTransform;
	import flash.system.Security;
	import flash.system.SecurityPanel;
	import flash.utils.Timer;
	
	public class BasicMicro extends EventDispatcher{
		
		private static var _instance:BasicMicro
		private var _micro:Microphone;
		private var _timer:Timer;
		private var _gains_ar:Array;
		
		public function BasicMicro(s:SingletonEnforcer){
		}
		
		public static function getInstance ():BasicMicro{
			if(!_instance){
				_instance=new BasicMicro(new SingletonEnforcer);
			}
			return _instance;
		}

		public function getMicro():Microphone{
			
			_gains_ar=new Array();
			_timer=new Timer(100,10);
			_timer.addEventListener(TimerEvent.TIMER,gainControl);
			_timer.addEventListener(TimerEvent.TIMER_COMPLETE,stopGainControl);
			
			if(_micro!=null){
				return _micro;
			}else{
				_micro=Microphone.getMicrophone();
				_micro.setUseEchoSuppression(true);
				_micro.gain=100;
				_micro.rate = 44;
				_micro.setLoopBack(true);
				_micro.setUseEchoSuppression(true);
				_micro.setSilenceLevel(0);
				_micro.soundTransform = new SoundTransform(0);
				if(_micro==null){
					Security.showSettings(SecurityPanel.MICROPHONE);
					_micro=new Microphone();
				}
			}
			if (_micro.muted){
				Security.showSettings(SecurityPanel.PRIVACY);
			}
			_micro.addEventListener(ActivityEvent.ACTIVITY, activityHandler);
			return _micro;
		}
		
		private function activityHandler(event:ActivityEvent):void{
			 if (event.activating == true){ 
				_timer.start();
			} 
		}
		
		private function 	stopGainControl(event:TimerEvent):void{
			_timer.removeEventListener(TimerEvent.TIMER,gainControl);
			_timer.removeEventListener(TimerEvent.TIMER_COMPLETE,stopGainControl);
			var tmp:uint=0;
			for(var i:uint=0;i<_gains_ar.length;i++){
				tmp+=_gains_ar[i];
			}
			_micro.gain=90-tmp/i;
		
		}
		
		private function gainControl(event:TimerEvent):void{
			_gains_ar.push(_micro.activityLevel);
		}

	}
}
class SingletonEnforcer{}